<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}
require_once 'track_online.php';
// 当前用户
$currentUser = $_SESSION['username'];

// 定义路径
$qlDir = __DIR__ . '/ql';
$infoFile = $qlDir . '/info.json';

// 初始化群聊文件夹和信息文件
if (!is_dir($qlDir)) {
    mkdir($qlDir, 0777, true);
}
if (!file_exists($infoFile)) {
    file_put_contents($infoFile, json_encode([]));
}

// 确保 $groups 是数组
$groups = json_decode(file_get_contents($infoFile), true);
if (!is_array($groups)) {
    $groups = [];
}

// 处理创建群聊逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理解散群聊请求
    if (isset($_POST['action']) && $_POST['action'] === 'disband_group' && isset($_POST['group_id'])) {
        $groupId = $_POST['group_id'];
        
        // 验证当前用户是否有权限解散这个群聊（群主）
        if (isset($groups[$groupId]) && $groups[$groupId]['creator'] === $currentUser) {
            // 1. 从群聊列表中移除
            unset($groups[$groupId]);
            file_put_contents($infoFile, json_encode($groups));
            
            // 2. 删除群聊文件夹
            $groupDir = $qlDir . '/' . $groupId;
            if (is_dir($groupDir)) {
                // 递归删除文件夹及其内容
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($groupDir, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                
                foreach ($files as $fileinfo) {
                    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                    $todo($fileinfo->getRealPath());
                }
                
                rmdir($groupDir);
            }
            
            // 3. 从所有成员的聊天列表中移除
            $membersFile = $qlDir . '/' . $groupId . '/members.json';
            if (file_exists($membersFile)) {
                $members = json_decode(file_get_contents($membersFile), true);
                if (is_array($members)) {
                    foreach ($members as $member) {
                        $userChatFile = __DIR__ . "/user/$member/chats.json";
                        if (file_exists($userChatFile)) {
                            $userChats = json_decode(file_get_contents($userChatFile), true);
                            $userChats = array_filter($userChats, function($chat) use ($groupId) {
                                return $chat['id'] !== $groupId;
                            });
                            file_put_contents($userChatFile, json_encode(array_values($userChats)));
                        }
                    }
                }
            }
            
            // 4. 删除成员文件
            if (file_exists($membersFile)) {
                unlink($membersFile);
            }
            
            // 5. 删除消息文件
            $messagesFile = $qlDir . '/' . $groupId . '/messages.json';
            if (file_exists($messagesFile)) {
                unlink($messagesFile);
            }
            
            // 重定向到当前页面（强制刷新）
            echo "<script>alert('群聊已成功解散'); location.href='qlcreat.php';</script>";
            exit();
        } else {
            echo "<script>alert('您没有权限解散此群聊');</script>";
            exit();
        }
    }
    
    // 处理创建新群聊
    $groupName = trim($_POST['group_name']);
    $groupDescription = trim($_POST['group_description']);
    $groupTags = trim($_POST['group_tags']);
    $groupAvatar = isset($_FILES['group_avatar']) ? $_FILES['group_avatar'] : null;

    // 检查文件上传错误
    if ($groupAvatar && $groupAvatar['error'] !== UPLOAD_ERR_OK && $groupAvatar['error'] !== UPLOAD_ERR_NO_FILE) {
        $errorMsg = "文件上传失败: ";
        switch ($groupAvatar['error']) {
            case UPLOAD_ERR_INI_SIZE:
                $errorMsg .= "文件大小超过服务器限制";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $errorMsg .= "文件大小超过表单限制";
                break;
            case UPLOAD_ERR_PARTIAL:
                $errorMsg .= "文件只有部分被上传";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $errorMsg .= "缺少临时文件夹";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $errorMsg .= "写入文件失败";
                break;
            default:
                $errorMsg .= "未知错误";
        }
        echo "<script>alert('$errorMsg');</script>";
        exit();
    }

    // 检查文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if ($groupAvatar && $groupAvatar['error'] === UPLOAD_ERR_OK) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $groupAvatar['tmp_name']);
        finfo_close($finfo);
        
        if (!in_array($mime, $allowedTypes)) {
            echo "<script>alert('只允许上传 JPG, PNG 或 GIF 图片');</script>";
            exit();
        }
    }

    // 检查群聊名称是否重复
    foreach ($groups as $group) {
        if ($group['name'] === $groupName) {
            echo "<script>alert('群聊名称已存在，请换一个名称');</script>";
            exit();
        }
    }

    // 检查表单内容是否完整
    if (empty($groupName) || empty($groupDescription)) {
        echo "<script>alert('群聊名称和描述不能为空');</script>";
        exit();
    }

    // 创建群聊
    $groupID = uniqid(); // 生成唯一群聊ID
    $uploadsDir = $qlDir . '/' . $groupID;
    
    // 确保上传目录存在
    if (!is_dir($uploadsDir)) {
        mkdir($uploadsDir, 0777, true);
    }

    // 上传头像
    if ($groupAvatar && $groupAvatar['error'] === UPLOAD_ERR_OK) {
        // 生成唯一的文件名
        $fileExtension = pathinfo($groupAvatar['name'], PATHINFO_EXTENSION);
        $avatarFileName = uniqid('avatar_') . '.' . $fileExtension;
        $avatarPath = $uploadsDir . '/' . $avatarFileName;
        
        if (move_uploaded_file($groupAvatar['tmp_name'], $avatarPath)) {
            // 存储相对路径用于显示
            $avatarRelativePath = "ql/$groupID/$avatarFileName";
        } else {
            $avatarRelativePath = "default-avatar.png";
        }
    } else {
        $avatarRelativePath = "default-avatar.png";
    }

    // 创建成员文件
    $membersFile = $uploadsDir . '/members.json';
    $members = [$currentUser]; // 初始成员只有创建者
    file_put_contents($membersFile, json_encode($members));
    
    // 创建消息文件
    $messagesFile = $uploadsDir . '/messages.json';
    file_put_contents($messagesFile, json_encode([]));

    // 保存群聊信息到 info.json
    $groups[$groupID] = [
        'creator' => $currentUser, // 记录创建者
        'name' => $groupName,
        'description' => $groupDescription,
        'tags' => $groupTags,
        'avatar' => $avatarRelativePath,
        'created_at' => date('Y-m-d H:i:s'), // 记录创建时间
        'admins' => [$currentUser], // 设置创建者为管理员
    ];
    file_put_contents($infoFile, json_encode($groups));

    // 更新用户聊天列表
    $userChatFile = __DIR__ . "/user/$currentUser/chats.json";
    if (!file_exists($userChatFile)) {
        file_put_contents($userChatFile, json_encode([]));
    }
    $userChats = json_decode(file_get_contents($userChatFile), true);

    $userChats[] = [
        'id' => $groupID,
        'name' => $groupName,
        'type' => 'group',
        'avatar' => $avatarRelativePath,
        'creator' => $currentUser, // 记录创建者
        'created_at' => date('Y-m-d H:i:s'), // 记录创建时间
    ];
    file_put_contents($userChatFile, json_encode($userChats));

    // 提示创建成功并返回
    echo "<script>alert('群聊创建成功！您的群聊号是 $groupID'); location.href='qlcreat.php';</script>";
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建群聊</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            height: 100vh;
            overflow: hidden;
        }
        
        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: linear-gradient(90deg, #1a2a6c, #2a5298);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            z-index: 100;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
        }
        
        .join-btn {
            background: #2ecc71;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 20px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 3px 8px rgba(0,0,0,0.15);
        }
        
        .join-btn:hover {
            background: #27ae60;
            transform: translateY(-2px);
        }
        
        /* 主内容区 */
        .content-container {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 70px);
            margin-top: 70px;
        }
        
        .content-header {
            padding: 20px;
            background: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            z-index: 10;
        }
        
        .create-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }
        
        .create-btn i {
            margin-right: 10px;
        }
        
        .create-btn:hover {
            background: linear-gradient(135deg, #2980b9, #1a5a8d);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(52, 152, 219, 0.4);
        }
        
        .content-description {
            margin-top: 15px;
            color: #718096;
            font-size: 14px;
            text-align: center;
        }
        
        /* 群聊列表容器 */
        .groups-container {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            background-color: #f0f2f5;
        }
        
        .group-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        @media (max-width: 768px) {
            .group-grid {
                grid-template-columns: 1fr;
            }
        }
        
        .group-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .group-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .group-avatar {
            width: 100%;
            height: 160px;
            object-fit: cover;
            background: linear-gradient(135deg, #3498db, #2c3e50);
        }
        
        .group-details {
            padding: 15px;
        }
        
        .group-name {
            font-size: 18px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .group-id {
            font-size: 12px;
            color: #718096;
            background: #f0f2f5;
            padding: 3px 8px;
            border-radius: 10px;
        }
        
        .group-description {
            font-size: 14px;
            color: #4a5568;
            margin-bottom: 12px;
            line-height: 1.5;
            height: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }
        
        .group-meta {
            display: flex;
            justify-content: space-between;
            color: #718096;
            font-size: 13px;
            border-top: 1px solid #f0f2f5;
            padding-top: 12px;
            margin-top: 12px;
        }
        
        .group-creator {
            display: flex;
            align-items: center;
        }
        
        .group-creator-icon {
            width: 24px;
            height: 24px;
            background: #e9ecef;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-size: 12px;
        }
        
        .actions {
            display: flex;
            justify-content: center;
            margin-top: 12px;
        }
        
        .delete-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .delete-btn:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }
        
        .no-groups {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            padding: 40px 20px;
            text-align: center;
            margin: 20px auto;
            max-width: 500px;
        }
        
        .no-groups i {
            font-size: 50px;
            color: #bdc3c7;
            margin-bottom: 15px;
        }
        
        .no-groups p {
            font-size: 16px;
            color: #718096;
            margin-top: 15px;
        }
        
        /* 创建群聊弹窗 */
        .popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}
        
       .popup-content {
    background: white;
    width: 90%;
    max-width: 450px;
    border-radius: 15px;
    box-shadow: 0 15px 30px rgba(0,0,0,0.3);
    overflow: hidden;
    max-height: 90vh; /* 限制最大高度 */
    overflow-y: auto; /* 添加垂直滚动 */
    transform: scale(1);
    transition: transform 0.3s ease; /* 添加缩放动画 */
}

/* 手机上的优化 */
@media (max-height: 750px) {
    .popup-content {
        transform: scale(0.9); /* 缩小弹窗 */
    }
}

@media (max-height: 650px) {
    .popup-content {
        transform: scale(0.85); /* 进一步缩小 */
    }
}

@media (max-height: 580px) {
    .popup-content {
        transform: scale(0.8); /* 更小屏幕进一步缩小 */
    }
}

        
        .popup-header {
            background: linear-gradient(90deg, #1a2a6c, #2a5298);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .popup-header h2 {
            font-size: 22px;
            margin: 0;
        }
        
       .popup-body {
    padding: 20px; /* 适当减少内边距 */
}
@media (max-width: 480px) {
    .popup-body {
        padding: 15px;
    }
    .popup-header h2 {
        font-size: 19px; /* 标题缩小 */
    }
    .form-group {
        margin-bottom: 15px; /* 减少间距 */
    }
    .form-control {
        padding: 10px 12px; /* 输入框缩小 */
        font-size: 14px;
    }
    .form-control.textarea {
        min-height: 90px; /* 文本区域高度减小 */
    }
    #avatarPreview {
        width: 100px; /* 头像预览缩小 */
        height: 100px;
    }
    .submit-btn, 
    .cancel-btn {
        padding: 10px; /* 按钮高度减小 */
    }
}

/* 添加最大高度以防止溢出 */
@media (max-height: 580px) {
    .popup-content {
        max-height: 85vh;
    }
    .form-control.textarea {
        min-height: 70px;
    }
    #avatarPreview {
        width: 80px;
        height: 80px;
    }
}
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #2d3748;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
            outline: none;
        }
        
        .form-control.textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .form-footer {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        .submit-btn {
            flex: 1;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .submit-btn:hover {
            background: linear-gradient(135deg, #2980b9, #1a5a8d);
        }
        
        .cancel-btn {
            flex: 1;
            background: #e2e8f0;
            color: #4a5568;
            border: none;
            padding: 12px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .cancel-btn:hover {
            background: #cbd5e0;
        }
        
        .file-input {
            display: block;
            width: 100%;
            padding: 12px;
            background: #f0f2f5;
            border: 1px dashed #cbd5e0;
            border-radius: 10px;
            text-align: center;
            color: #718096;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .file-input:hover {
            background: #e2e8f0;
            border-color: #a0aec0;
        }
        
        /* 头像预览样式 */
        #avatarPreview {
            width: 120px;
            height: 120px;
            margin: 10px auto;
            border-radius: 50%;
            overflow: hidden;
            background-color: #f0f2f5;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px dashed #cbd5e0;
        }
        
        #avatarPreview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .file-hint {
            text-align: center;
            font-size: 12px;
            color: #718096;
            margin-top: 5px;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-header {
                padding: 15px;
            }
            
            .groups-container {
                padding: 10px;
            }
            
            .popup-body {
                padding: 20px;
            }
        }
        
        @media (max-width: 480px) {
            .navbar {
                padding: 12px 15px;
            }
            
            .back-btn {
                font-size: 16px;
                width: 32px;
                height: 32px;
            }
            
            .navbar-title {
                font-size: 16px;
            }
            
            .join-btn {
                padding: 6px 12px;
                font-size: 14px;
            }
            
            .content-container {
                margin-top: 60px;
            }
            
            .create-btn {
                padding: 10px 20px;
                font-size: 15px;
            }
            
            .group-description {
                height: auto;
                -webkit-line-clamp: 2;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="location.href='index.php'">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">创建群聊</div>
        <button class="join-btn" onclick="location.href='qljoin.php'">
            <i class="fas fa-users"></i> 加入群聊
        </button>
    </div>
    
    <!-- 主内容区 -->
    <div class="content-container">
        <div class="content-header">
            <button class="create-btn" onclick="togglePopup()">
                <i class="fas fa-plus"></i> 创建新群聊
            </button>
            <div class="content-description">您创建的群聊将会显示在这里</div>
        </div>
        
        <div class="groups-container">
            <?php if (count($groups) === 0): ?>
                <div class="no-groups">
                    <i class="fas fa-users-slash"></i>
                    <h3>您还没有创建任何群聊</h3>
                    <p>点击上面的按钮创建您的第一个群聊</p>
                </div>
            <?php else: ?>
                <div class="group-grid">
                    <?php foreach ($groups as $id => $group): ?>
                        <?php if ($group['creator'] === $currentUser): ?>
                            <div class="group-card">
                                <?php 
                                // 正确处理头像路径
                                $avatarPath = $group['avatar'];
                                $isDefaultAvatar = ($avatarPath === 'default-avatar.png');
                                $avatarPath = $isDefaultAvatar ? 'default-avatar.png' : $avatarPath;
                                ?>
                                <img src="<?= htmlspecialchars($avatarPath) ?>" alt="群头像" class="group-avatar">
                                <div class="group-details">
                                    <div class="group-name">
                                        <?= htmlspecialchars($group['name']) ?>
                                        <span class="group-id">ID: <?= $id ?></span>
                                    </div>
                                    <div class="group-description">
                                        <?= htmlspecialchars($group['description']) ?>
                                    </div>
                                    <div class="group-meta">
                                        <div class="group-creator">
                                            <div class="group-creator-icon">
                                                <i class="fas fa-crown"></i>
                                            </div>
                                            <?= htmlspecialchars($group['creator']) ?> (群主)
                                        </div>
                                        <div>
                                            <?= date('Y-m-d', strtotime($group['created_at'])) ?>
                                        </div>
                                    </div>
                                    <div class="actions">
                                        <form method="POST" style="width:100%">
                                            <input type="hidden" name="action" value="disband_group">
                                            <input type="hidden" name="group_id" value="<?= $id ?>">
                                            <button type="submit" class="delete-btn" onclick="return confirm('确定要解散该群聊吗？此操作将永久删除所有群聊数据！')">
                                                <i class="fas fa-trash"></i> 解散群聊
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- 创建群聊弹窗 -->
    <div class="popup" id="createPopup">
        <div class="popup-content">
            <div class="popup-header">
                <h2>创建新群聊</h2>
            </div>
            <div class="popup-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="group_name">群聊名称</label>
                        <input type="text" name="group_name" class="form-control" placeholder="输入群聊名称" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="group_description">群聊介绍</label>
                        <textarea name="group_description" class="form-control textarea" placeholder="输入群聊介绍..." required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="group_tags">群聊标签</label>
                        <input type="text" name="group_tags" class="form-control" placeholder="例如：游戏、学习、技术交流">
                    </div>
                    
                    <div class="form-group">
                        <label for="group_avatar">群聊头像</label>
                        <div id="avatarPreview">
                            <i class="fas fa-camera" style="font-size: 40px; color: #ccc;"></i>
                        </div>
                        <label for="group_avatar" class="file-input">
                            <i class="fas fa-cloud-upload-alt"></i> 选择群聊头像
                            <input type="file" name="group_avatar" id="group_avatar" accept="image/*" style="display: none;" onchange="previewAvatar(event)">
                        </label>
                        <p class="file-hint">支持 JPG, PNG, GIF 格式，最大 2MB</p>
                    </div>
                    
                    <div class="form-footer">
                        <button type="submit" class="submit-btn">创建群聊</button>
                        <button type="button" class="cancel-btn" onclick="togglePopup()">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function togglePopup() {
            const popup = document.getElementById('createPopup');
            popup.style.display = popup.style.display === 'flex' ? 'none' : 'flex';
        }
        
        function previewAvatar(event) {
            const input = event.target;
            const preview = document.getElementById('avatarPreview');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    preview.innerHTML = '';
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.width = '100%';
                    img.style.height = '100%';
                    img.style.objectFit = 'cover';
                    preview.appendChild(img);
                }
                
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>